<template>
  <el-upload action="" :auto-upload="false" accept=".json" :multiple="false" :show-file-list="false" :on-change="JsonLoad">
    <el-button slot="trigger" icon="el-icon-upload"></el-button>
  </el-upload>
</template>

<script>
  export default {
    data: () => {
      return {
        reader: null
      }
    },
    methods: {
      JsonLoad (file) {
        return new Promise((resolve, reject) => {
          // 检验是否支持 FileRender
          if (typeof FileReader === 'undefined') {
            reject('当前浏览器不支持FileReader')
          }
          // 执行读取json数据操作
          this.reader = new FileReader()
          this.reader.readAsText(file.raw)
          this.reader.onerror = (error) => {
            reject('json 文件解析失败', error)
          }
          this.reader.onload = () => {
            if (this.reader.result) {
              try {
                resolve(JSON.parse(this.reader.result))
              } catch (error) {
                reject('读取数据解析失败', error)
              }
            } else {
              reject('读取数据解析失败', error)
            }
          }
        }).then((res) => {
          this.$emit('data-update', res)
        })
      }
    }
  }
</script>